import { ElMessage } from 'element-plus'

let baseURL = 'http://localhost:3000'

async function myFetch(url,options){
    //请求前自定义 request
    if(!/^http/.test(url)) url = baseURL + url
    options = options || {}
    let headers = options.headers || {}
    headers['Content-Type'] = headers['Content-Type'] || 'application/json'
    let token = sessionStorage.getItem('token')
    if(token) headers.token = token

    let res = await (await fetch(url,{
        method:options.method || 'GET',
        headers,
        body:JSON.stringify(options.data)
      })).json()
      
    //返回内容自定义 response
    if(res.errorMsg) ElMessage.error(res.errorMsg)
    if(res.code == 400 || res.code == 401 || res.code == 402) {
        location.href = '#/login'
    }else{
        return res
    }
}

export default myFetch

export const get = async (url,query,headers)=>{
    let queryString = ''
    query = query || {}
    for(let key in query) queryString += `&${key}=${query[key]}`
    //&id=1&name=2
    if(url.indexOf('?') > -1){
        url += queryString
    }else{
        url += queryString.replace('&','?')
    }
    return await myFetch(url,{
        headers
    })
}
export const post = async (url,data,headers)=>{
    return await myFetch(url,{
        method:'POST',
        headers,
        data
    })
}
export const put = async (url,data,headers)=>{
    return await myFetch(url,{
        method:'PUT',
        headers,
        data
    })
}
export const delet = async (url,query,headers)=>{
    let queryString = ''
    query = query || {}
    for(let key in query) queryString += `&${key}=${query[key]}`
    //&id=1&name=2
    if(url.indexOf('?') > -1){
        url += queryString
    }else{
        url += queryString.replace('&','?')
    }
    return await myFetch(url,{
        method:'DELETE',
        headers
    })
}